<template>
  <div class="park-sroll">
    <div class="park-sroll-info">  
      <el-scrollbar height="100%" @scroll="scroll" always  ref="scrollbarRef">
        <div ref="innerRef">
          <slot></slot> 
        </div>
        <div v-if="isEnd" class="park-sroll-end">
          <el-divider> 到底部了 </el-divider>
        </div>
        <div v-if="loading" class="park-sroll-loading" v-loading="loading"></div>
        <div class="park-sroll-blank"></div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineEmits, defineExpose, defineProps } from 'vue'
const scrollbarRef = ref(null)
const innerRef = ref()
const emits = defineEmits(['scrolltolower'])
const value = ref(0)
const oldTop = ref(0)
const props = defineProps({
  loading:{
    type:Boolean,
    default: false
  },
  isEnd: {
    type:Boolean,
    default: false
  }
})

const handleScroll =({ scrollTop }) => {
  value.value = scrollTop
  if (props.loading || props.isEnd) {
    return
  }
  if ((innerRef.value.clientHeight - document.body.offsetHeight - scrollTop) <= 50) {
    emits('scrolltolower')
    console.log('-------触发------')
  }
}

const scroll = debounce(handleScroll, 300)
 
const scrollToBottom = () => {
  if (scrollbarRef.value && innerRef.value) {
    scrollbarRef.value.setScrollTop(innerRef.value.clientHeight)
  }
}

const setScrollToTop = () => {
  scrollbarRef.value.setScrollTop(0)
}


// 防抖函数
function debounce(fn, delay) {
  let timeoutId = null
  return function (...args) {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

defineExpose({
  scrollbarRef,
  setScrollToTop,
  scrollToBottom
})

onMounted(() => {
  setTimeout(() => {
    oldTop.value = innerRef.value.clientHeight
    scrollToBottom()
  }, 100)
})

onUnmounted(() => {
})
</script>

<style lang="scss" scoped>
::v-deep .el-divider__text{
  background-color: #f4f2ee!important
}
::v-deep .el-loading-mask{
  background-color: #f4f2ee!important
}
.park-sroll{
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  &-info{
    overflow: hidden;
  }
  &-end{
    width: 300px;
    margin: 50px auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  &-loading{
    height: 60px;
    background: #f4f2ee;
    padding-bottom: 100px;
  }
  &-blank{
    padding-bottom: 60px;
  }
}
</style>